function editPost(form){
    form_data = praseForm(form);
    var req_form_vars = ['title','body'];
    if(formValidate(req_form_vars))
        return false;
    var success_function = function(return_data){
	return_data = JSON.parse(return_data.responseText);
	if(return_data['success'] && return_data['id'])
	    window.location = '/post/' + return_data['id'];
    }
    var post_data = 'action=edit&title=' + form_data['title'] + '&body=' + form_data['body'] + '&hidden=' + form_data['hidden'];
    ajaxin('/post/edit/' + form_data['post_id'],true,post_data,success_function,true);
    return false;
}

function submitComment(form){
    form_data = praseForm(form);
    var req_form_vars = ['comment_name','comment_email','comment_body'];
    if(formValidate(req_form_vars))
        return false;
    var successFunction = function(return_data){
        return_data = JSON.parse(return_data.responseText);
        var response_span = document.createElement('span');
        if(return_data['success']){
            for(i in req_form_vars)
                document.getElementById(req_form_vars[i]).value = '';
            response_span.innerHTML = 'Your comment has been submitted for approval to the admin, once approved it will be shown below';
        }else{
            response_span.class = 'font-red';
            response_span.innerHTML = 'There was an issue submitting your comment - Please try again!';
        }
        response_span.style.marginBottom = '10px';
        document.getElementById('comment_form').appendChild(response_span);
    }
    var new_comment = 'body='+form_data['comment_body']+'&name='+form_data['comment_name']+'&email='+form_data['comment_email'];
    ajaxin('/post/comment/'+form_data['post_id'],true,new_comment,successFunction,true);
    return false;
}

function submitPost(form){
    form_data = praseForm(form);
    var req_form_vars = ['title','body'];
    if(formValidate(req_form_vars))
        return false;
    var success_function = function(return_data){
	return_data = JSON.parse(return_data.responseText);
        console.log(return_data);
	if(return_data['success'])
	    window.location = '/post/' + return_data['post_id'];
    }
    var new_post = 'action=new&title=' + form_data['title'] + '&body=' + form_data['body'] + '&hidden=' + form_data['hidden'];
    ajaxin('/post/new',true,new_post,success_function,true);
    return false;
}

function submitLogin(form){
    form_data = praseForm(form);
    var req_form_vars = ['username','password'];
    if(formValidate(req_form_vars))
        return false;
    var err_el = document.getElementById('login_error');
    err_el.style.display = 'none';
    var success_function = function(return_data){
	return_data = JSON.parse(return_data.responseText);
	if(return_data['logged_in'])
	    window.location = '/';
	else
	    err_el.style.display = '';
    }
    var credentials = 'username=' + form_data['username'] + '&password=' + form_data['password'];
    document.getElementById('username').value = '';
    document.getElementById('password').value = '';
    ajaxin('/login',true,credentials,success_function,true);
    return false;
}

//Admin Comments. You're not going to get far trying to replicate this POST - the backend obviously expects the proper cookies in the request
function handleComment(id,approval,comment_element){
    var return_handler = function(http){
        var return_data = JSON.parse(http.responseText);
        if(return_data['success'])
            comment_element.parentNode.parentNode.parentNode.removeChild(comment_element.parentNode.parentNode);
            
    };
    var comment_post = 'approve=' + approval+'&ID='+id;
    ajaxin('/admin/comments',true,comment_post,return_handler,true);
    return false;
}

//Shared Functions
var transCallName = function(){
    var UA = navigator.userAgent.toLowerCase();
    var browsers = {'msie': 'msTransitionEnd','firefox': 'transitionend','opera':'oTransitionEnd','webkit': 'webkitTransitionEnd'};
    for(browser in browsers){
        if(UA.indexOf(browser) > -1)
            return browsers[browser];
    }
    return false;
};
function praseForm(form){
    var return_data = Array();
    form = form.elements;
    for(el in form){
	switch(form[el].type){
	    case 'text':
	    case 'password':
	    case 'textarea':
            case 'hidden':
		return_data[form[el].id] = encodeURIComponent(form[el].value);
		break;
            case 'checkbox':
                return_data[form[el].id] = encodeURIComponent(form[el].checked);
                break;
	    default:
		break;
	}
    }
    return return_data;
}

function formValidate(required){
    var failure = false;
    for(i in required){
        var form_el = document.getElementById(required[i]);
        classes = form_el.className;
        if(!form_el.value){
            if(classes.search('input-error') < 0)
                form_el.className = classes + ' input-error';
            failure = true;
        }else{
            form_el.className = classes.replace('input-error', '');
        }
    }
    return failure;
}

function getDate(){
    var date = new Date();
    return date.getFullYear()+''+(date.getMonth()+1)+''+date.getDate()+ '-' + date.getHours() + '' + date.getMinutes() + '' + date.getSeconds();
}

function uploadFile(file){
    var upload = getId('file_upload'),drop_area = getId('file_drop_area'),uploaded = getId('file_list');
    var li = document.createElement('li'),div = document.createElement('div'),progress_div = document.createElement('div'),
	progress = document.createElement('div'),
	reader,xhr,fileInfo;
    li.appendChild(div);
    progress_div.className = 'progress-bar-container';
    progress.className = 'progress-bar';
    progress_div.appendChild(progress);
    li.appendChild(progress_div);
    xhr = new XMLHttpRequest();
    xhr.upload.addEventListener('progress',function(evt){
        if(evt.lengthComputable)
            progress.style.width = (evt.loaded / evt.total) * 100 + "%";
    },false);
    xhr.addEventListener('load',function(){
        progress_div.className += " uploaded";
        progress.innerHTML = "Uploaded!";
    },false);
    xhr.open('post', "/upload", true);
    var file_name = 'image-'+getDate()+'.jpg';
    console.log(file_name);
    xhr.setRequestHeader("Content-Type", "multipart/form-data");
    xhr.setRequestHeader("X-File-Name", file_name);
    xhr.setRequestHeader("X-File-Size", file.size);
    xhr.setRequestHeader("X-File-Type", file.type);
    xhr.send(file);
    // Present file info and append it to the list of files
    fileInfo = '<span>Name: ' + file_name + ' Size:</strong> ' + parseInt(file.size / 1024, 10) + ' kb ';
    div.innerHTML = fileInfo;
    uploaded.appendChild(li);
}

function getId(id){
    return document.getElementById(id);
}

function doLogout(){
    var check = confirm('Are you sure you want to logout?');
    if(!check)
        return false;
    var cookies = document.cookie.split(";");
    var date = new Date();
    date.setTime(date.getTime()+(-1*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
    for (var i = 0; i < cookies.length; i++){
        if(cookies[i].search('psb') >= 0)
            document.cookie=cookies[i].split("=")[0]+"="+';'+expires+"; path=/";
    }
    window.location = '/';
    return false;
}

//Sidebar
function toggleSidebar(){
    var sidebar = document.getElementsByClassName('sidebar').item(0);
    var side_toggler = document.getElementById('sidebar_toggler');
    var content = document.getElementById('content');
    if(sidebar.style.display != 'none'){
        side_toggler.className = 'sidebar-toggle-on';
        content.style.marginRight = '1%';
        sidebar.style.display = 'none';
    }else{
        var browser_type = transCallName();
        if(browser_type){
            var trans_handler = function(){
                content.removeEventListener(browser_type,trans_handler, false);
                sidebar.style.display = '';
                sidebar.style.width = '25%';
            };
            content.addEventListener(browser_type, trans_handler , false );
        }else{
            sidebar.style.display = '';
            sidebar.style.width = '25%';
        }
        document.getElementById('content').style.marginRight = '20%';
        side_toggler.className ='sidebar-toggle';
    }
}

window.onload = function(){
    var $createSideToggle = function(){
        var container = document.getElementById('content');
        var span = document.createElement('span');
        span.setAttribute('onclick','return toggleSidebar();');
        span.id = 'sidebar_toggler';
        span.className ='sidebar-toggle';
        span.style.height = container.offsetHeight;
        return container.appendChild(span);
    };
    $createSideToggle();
    // Resize the sidebar if the size of the container changes
    setInterval(function(){getId('sidebar_toggler').style.height = getId('content').offsetHeight;},1000);
    //Create event listener for uploads
    if(window.File && window.FileList && window.FileReader){
        var upload = document.getElementById('file_upload');
        if(upload){ //< Make sure we have a page with an upload form.
            var drop_area = document.getElementById('file_drop_area');
            var uploaded = document.getElementById('file_list');
            upload.addEventListener('change',function(){
                var files = this.files;
                if(files){
                for(var i=0, l=files.length; i<l; i++)
                    uploadFile(files[i]);
                }else{
                    uploaded.innerHTML = 'No support for the File API in this web browser';
                }
            },false);
            drop_area.addEventListener('dropleave',function(evt){
                    var target = evt.target;
                    if (target && target === drop_area)
                        this.className = '';
                    evt.preventDefault();
                    evt.stopPropagation();
            },false);
            drop_area.addEventListener('dragenter',function(evt){
                this.className = '';
                evt.preventDefault();
                evt.stopPropagation();
            },false);
            drop_area.addEventListener('dragover',function(evt){
                evt.preventDefault();
                evt.stopPropagation();
            },false);
            drop_area.addEventListener('drop',function(evt){
                traverseFiles(evt.dataTransfer.files);
                this.className = '';
                evt.preventDefault();
                evt.stopPropagation();
            },false);
        }
    }
    return false;
}